const express = require('express');
const router = express.Router();
const { Product, Category, Brand } = require('../models');

// 获取商品列表
router.post('/list', async (req, res) => {
  try {
    const { current = 1, pageSize = 10, ...filters } = req.body;
    const skip = (Number(current) - 1) * Number(pageSize);
    
    const query = {};
    // 处理筛选条件
    if (filters.name) query.name = new RegExp(filters.name, 'i');
    if (filters.categoryId) query.categoryId = filters.categoryId;
    if (filters.brandId) query.brandId = filters.brandId;
    if (filters.status !== undefined) query.status = filters.status === 'true';

    const total = await Product.countDocuments(query);
    const list = await Product.find(query)
      .sort({ sort: 1 })
      .skip(skip)
      .limit(Number(pageSize));

    res.json({
      code: 200,
      data: {
        list,
        total,
        current: Number(current),
        pageSize: Number(pageSize)
      }
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: '获取商品列表失败'
    });
  }
});

// 创建商品
router.post('/create', async (req, res) => {
  try {
    const {
      name,
      categoryId,
      categoryName,
      brandId,
      brandName,
      mainImage,
      images,
      purchasePrice,
      marketPrice,
      shareRatio,
      recoveryPrice,
      platformProfit,
      userProfit,
      batchNo,
      specification,
      unit,
      precautions,
      purchasePriceDate,
      remark,
      sort,
      status,
      priceHistory
    } = req.body;

    // 生成唯一ID
    const timestamp = new Date().getTime();
    const random = Math.floor(Math.random() * 1000);
    const id = `${timestamp}${random}`;

    const productData = {
      id,
      name,
      categoryId,
      categoryName,
      brandId,
      brandName,
      mainImage,
      images: Array.isArray(images) ? images : [images],
      purchasePrice: Number(purchasePrice),
      marketPrice: Number(marketPrice),
      shareRatio: Number(shareRatio) || 0.3,
      recoveryPrice: Number(recoveryPrice),
      platformProfit: Number(platformProfit),
      userProfit: Number(userProfit),
      batchNo,
      specification,
      unit,
      precautions,
      purchasePriceDate: purchasePriceDate ? new Date(purchasePriceDate) : null,
      remark,
      sort: Number(sort) || 0,
      status: status !== undefined ? Boolean(status) : true
    };

    // 处理价格历史数据
    if (Array.isArray(priceHistory)) {
      productData.priceHistory = priceHistory.map(record => ({
        date: new Date(record.date),
        marketPrice: Number(record.marketPrice),
        purchasePrice: Number(record.purchasePrice),
        shareRatio: Number(record.shareRatio) || 0.3,
        recoveryPrice: Number(record.recoveryPrice),
        platformProfit: Number(record.platformProfit),
        userProfit: Number(record.userProfit)
      }));
    }

    const product = await Product.create(productData);
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    console.error('创建商品错误:', error);
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 更新商品
router.post('/update', async (req, res) => {
  try {
    const { id, ...productData } = req.body;
    
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '商品ID不能为空'
      });
    }

    // 使用自定义 id 更新商品
    const product = await Product.updateProduct(id, productData);
    
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    console.error('Error updating product:', error);
    res.status(500).json({
      code:500,
      message: error.message || '更新商品失败'
    });
  }
});

// 删除商品
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '商品ID不能为空'
      });
    }

    const result = await Product.findOneAndDelete({ id: String(id) });
    if (!result) {
      return res.status(404).json({
        code:500,
        message: '商品不存在'
      });
    }

    return res.json({
      success: true,
      message: '删除成功'
    });
  } catch (err) {
    console.error('删除商品错误:', err);
    return res.status(500).json({
      code:500,
      message: '删除商品失败'
    });
  }
});

// 获取单个商品详情
router.post('/detail', async (req, res) => {
  try {
    const { id } = req.body;
    
    // 参数验证
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '商品ID不能为空'
      });
    }

    // 查询商品
    const product = await Product.findOne({ id });
    
    // 商品不存在处理
    if (!product) {
      return res.status(404).json({
        code:500,
        message: '商品不存在'
      });
    }

    // 返回成功结果
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    // 错误日志记录
    console.error('获取商品详情失败:', error);
    
    // 返回错误信息
    res.status(500).json({
      code:500,
      message: '获取商品详情失败',
      error: error.message
    });
  }
});

// 添加历史价格记录
router.post('/price-history/add', async (req, res) => {
  try {
    const { id, date, marketPrice, purchasePrice } = req.body;
    
    // 参数验证
    if (!id || !date || !marketPrice || !purchasePrice) {
      return res.status(400).json({
        code:500,
        message: '缺少必要参数'
      });
    }

    // 查找商品
    const product = await Product.findOne({ id });
    if (!product) {
      return res.status(404).json({
        code:500,
        message: '商品不存在'
      });
    }

    // 检查日期是否已存在
    const existingPriceIndex = product.priceHistory.findIndex(
      p => p.date.toISOString().split('T')[0] === new Date(date).toISOString().split('T')[0]
    );

    if (existingPriceIndex > -1) {
      // 更新已存在的价格记录
      product.priceHistory[existingPriceIndex] = {
        date: new Date(date),
        marketPrice: Number(marketPrice),
        purchasePrice: Number(purchasePrice)
      };
    } else {
      // 添加新的价格记录
      product.priceHistory.push({
        date: new Date(date),
        marketPrice: Number(marketPrice),
        purchasePrice: Number(purchasePrice)
      });
    }

    // 按日期排序
    product.priceHistory.sort((a, b) => a.date - b.date);

    // 保存更新
    await product.save();

    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    console.error('更新价格历史失败:', error);
    res.status(500).json({
      code:500,
      message: '更新价格历史失败',
      error: error.message
    });
  }
});

// 获取历史价格记录
router.get('/price-history/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { startDate, endDate } = req.query;
    
    const product = await Product.findOne({ id });
    if (!product) {
      return res.status(404).json({
        code:500,
        message: '商品不存在'
      });
    }

    let priceHistory = product.priceHistory;

    // 如果有日期范围，进行过滤
    if (startDate || endDate) {
      priceHistory = priceHistory.filter(record => {
        const recordDate = record.date.getTime();
        const start = startDate ? new Date(startDate).getTime() : -Infinity;
        const end = endDate ? new Date(endDate).getTime() : Infinity;
        return recordDate >= start && recordDate <= end;
      });
    }

    res.json({
      success: true,
      data: priceHistory
    });
  } catch (error) {
    console.error('获取价格历史失败:', error);
    res.status(500).json({
      code:500,
      message: '获取价格历史失败',
      error: error.message
    });
  }
});

// 获取商品详情（H5端）
router.post('/h5/detail', async (req, res) => {
  try {
    const { id } = req.body;
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '商品ID不能为空'
      });
    }

    const product = await Product.getProductForH5(id);
    
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    console.error('获取商品详情错误:', error);
    res.status(500).json({
      code:500,
      message: error.message || '获取商品详情失败'
    });
  }
});

// 复制商品
router.post('/copy', async (req, res) => {
  try {
    const { id } = req.body;
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '商品ID不能为空'
      });
    }

    const product = await Product.copyProduct(id);
    res.json({
      success: true,
      data: product
    });
  } catch (error) {
    console.error('复制商品失败:', error);
    res.status(500).json({
      code:500,
      message: error.message || '复制商品失败'
    });
  }
});

// H5商品列表
router.post('/h5/list', async (req, res) => {
  try {
    const { brandIds, categoryId, pageNum = 1, pageSize = 10 } = req.body;
    
    // 构建查询条件
    const findQuery = { status: 1 };
    if (Array.isArray(brandIds) && brandIds.length > 0) {
      findQuery.brandId = { $in: brandIds };
    }
    if (categoryId) {
      findQuery.categoryId = categoryId;
    }

    // 查询商品列表
    const products = await Product.find(findQuery)
      .sort({ sort: -1, _id: -1 })
      .skip((pageNum - 1) * pageSize)
      .limit(pageSize);

    // 获取总数
    const total = await Product.countDocuments(findQuery);

    // 处理每个商品的价格历史
    const list = products.map(product => {
      const productObj = product.toObject();
      
      // 获取最新的价格历史记录
      if (productObj.priceHistory && productObj.priceHistory.length > 0) {
        // 按日期排序，获取最新记录
        productObj.priceHistory.sort((a, b) => new Date(b.date) - new Date(a.date));
        const latestPrice = productObj.priceHistory[0];
          
        // 将最新价格数据提取到根级别
        productObj.purchasePrice = latestPrice.purchasePrice;
        productObj.recoveryPrice = latestPrice.recoveryPrice;
        productObj.userProfit = latestPrice.userProfit;
        productObj.purchasePriceDate = latestPrice.date;
      } else {
        // 如果没有价格历史，设置默认值
        productObj.purchasePrice = 0;
        productObj.recoveryPrice = 0;
        productObj.userProfit = 0;
        productObj.purchasePriceDate = null;
      }
      
      // 删除不需要的字段
      delete productObj.priceHistory;
      delete productObj.marketPrice;
      delete productObj.shareRatio;
      delete productObj.platformProfit;
      delete productObj.__v;
      
      return productObj;
    });

    res.json({
      success: true,
      data: {
        list,
        total,
        pageNum: Number(pageNum),
        pageSize: Number(pageSize)
      }
    });
  } catch (err) {
    console.error('获取H5商品列表失败:', err);
    res.json({
      code:500,
      message: err.message
    });
  }
});

module.exports = router; 